<?php

namespace App\Core\Event;

use App\Utils\LoggerHelper;
use Doctrine\Common\Annotations\Annotation\Enum;

abstract class HllEvent implements \JsonSerializable
{

    /**
     * 事件对应的动作，用作通用格式的消息存储
     * @var string|null
     */
    protected $action;

    /**
     * @var string
     * @Enum({"amqp"})
     */
    protected $transport;

    /**
     * @var string
     */
    protected $exchange;


    /**
     * @var MessageInterface
     */
    protected $playload;

    /**
     * @param MessageInterface $playload
     */
    public function __construct(MessageInterface $playload)
    {
        if (!$playload->getId()) {
            if (PHP_SAPI == 'cli') {
                $playload->setId(md5(uniqid()));
            } else {
                /** @var LoggerHelper $helper */
                $helper = app('logger_helper');
                $playload->setId($helper->getUniqueNO());
            }
        }
        $this->playload = $playload;
    }

    /**
     * @param MessageInterface $playload
     */
    public function setPlayload(MessageInterface $playload): void
    {
        $this->playload = $playload;
    }


    /**
     * @return string
     */
    public function getAction()
    {
        return $this->action;
    }


    /**
     * @return string
     */
    public function getTransport(): string
    {
        return $this->transport;
    }

    /**
     * @return string
     */
    public function getExchange(): string
    {
        return $this->exchange;
    }


    /**
     * @return string
     */
    public function getPlayload(): MessageInterface
    {
        return $this->playload;
    }

    /***
     * 消息对象序列号
     */
    public function messageSerial()
    {
        return objectSerial($this->getPlayload());
    }


    public function jsonSerialize()
    {
        return [
            'action' => $this->getAction(),
            'data' => $this->messageSerial()
        ];
    }

}
